package cn.nexttec.noteplayer.common


import android.app.Activity
import android.content.Context
import android.media.AudioManager
import android.util.DisplayMetrics
import kotlin.math.hypot
import kotlin.math.min

object GestureHelper {

    /**
     * 是否为平板设备（根据最小宽度 dp）
     */
    fun Context.isTablet(): Boolean {
        val metrics = resources.displayMetrics
        val widthDp = metrics.widthPixels / metrics.density
        val heightDp = metrics.heightPixels / metrics.density
        val smallestWidth = min(widthDp, heightDp)
        return smallestWidth >= 600
    }

    /**
     * 获取设备对角线英寸数（可选用来进一步区分）
     */
    fun Context.getScreenSizeInInches(): Double {
        val metrics = resources.displayMetrics
        val widthInches = metrics.widthPixels / metrics.xdpi
        val heightInches = metrics.heightPixels / metrics.ydpi
        return hypot(widthInches.toDouble(), heightInches.toDouble())
    }

    /**
     * 获取适配的手势灵敏度缩放因子（越大 = 越不敏感）
     */
    fun Context.getGestureSensitivityFactor(): Float {
        val screenSize = getScreenSizeInInches()
        return when {
            screenSize >= 10 -> 6.5f  // 大平板（更稳）
            screenSize >= 7 -> 5.0f   // 小平板
            isTablet()      -> 4.5f   // 未知平板（fallback）
            else            -> 3.5f   // 手机
        }
    }

    /**
     * 调整音量（deltaY 是你滑动距离，单位 px）
     */
    fun Context.adjustVolume(deltaY: Float, screenHeight: Int) {
        val factor = getGestureSensitivityFactor()
        val percent = deltaY / screenHeight
        val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        val delta = (maxVolume * percent / factor).toInt()

        if (delta != 0) {
            val newVolume = (currentVolume + delta).coerceIn(0, maxVolume)
            if (newVolume != currentVolume) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, AudioManager.FLAG_SHOW_UI)
            }
        }
    }

    /**
     * 调整屏幕亮度（Activity Context）
     */
    fun Activity.adjustBrightness(activity: Activity, deltaY: Float, screenHeight: Int) {
        val factor = activity.getGestureSensitivityFactor()
        val percent = deltaY / screenHeight / factor
        val lp = window.attributes
        val current = if (lp.screenBrightness < 0f) 0.5f else lp.screenBrightness
        val newBrightness = (current + percent).coerceIn(0.01f, 1f)
        lp.screenBrightness = newBrightness
        window.attributes = lp
    }
}
